package com.jung.customer.action;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;

import com.jung.common.Constants;
import com.jung.common.JqueryGridAction;
import com.jung.customer.model.Customer;
import com.jung.customer.service.CustomerService;
import com.opensymphony.xwork2.ActionContext;

public class CustomerAction extends JqueryGridAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final Log logger = LogFactory.getLog(CustomerAction.class);
	/**
	 * 总页数.
	 */
	private Integer total = 0;

	/**
	 * 总记录数.
	 */
	private Integer records = 0;

	/**
	 * 当前页数.
	 */
	private Integer page = 0;

	/**
	 * 排序字段名称.
	 */
	private String sidx = "";

	/**
	 * 排序方式.
	 */
	private String sord = "desc";

	/**
	 * 每页数量.
	 */
	private Integer rows;

	/**
	 * 查询结果列表.
	 */
	private List<Map<String, Object>> dataRows = new ArrayList<Map<String, Object>>();
	private String result;
	
	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}

	private int status;
	private int id;
	private int point;
	private String userName;
	private String password;
	private String email;
	private String realName;
	private String address;
	private String phone;
	private Date birth;
    public int getStatus() {
		return status;
	}

	public void setStatus(int status) {
		this.status = status;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public int getPoint() {
		return point;
	}

	public void setPoint(int point) {
		this.point = point;
	}
	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getRealName() {
		return realName;
	}

	public void setRealName(String realName) {
		this.realName = realName;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public Date getBirth() {
		return birth;
	}

	public void setBirth(Date birth) {
		this.birth = birth;
	}

	public CustomerService getCustomerService() {
		return customerService;
	}

	@Resource
	private CustomerService customerService;

	
	public void setCustomerService(CustomerService customerService) {
		this.customerService = customerService;
	}

	public String execute(){
		dataRows = new ArrayList<Map<String, Object>>();
		decodeQueryCondition();
		if (this.rows == null || this.rows <= 0) {
			int pagesize = Constants.DEFAULT_PAGE_SIZE;
			this.getPageContext().setPageSize(pagesize);
		} else
			this.getPageContext().setPageSize(rows);
		this.getPageContext().setPageNumber(page > 0 ? page - 1 : 0);
		// 获取支持当前查询的实体类型的查询服务接口定义
		try {
			setPageContext(customerService.getEntityPage(getPageContext(), getQueryConditions(),
					getSidx(), getSord()));
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		if (getPageContext()!= null && getPageContext().getPage() != null) {
			this.total = getPageContext().getPage().getLastPageNumber();
			this.records = getPageContext().getPage().getTotalNumberOfElements();
		}
		List entityList = this.getPageContext().getPage().getThisPageElements();
		if (entityList != null && entityList.size() > 0) {
			for (int i = 0; i < entityList.size(); i++) {
				Map<String, Object> dataitem = new HashMap<String, Object>();
				Object entity = entityList.get(i);
				// set rows
				Field[] fields = entity.getClass().getDeclaredFields();
				fields = removeStaticProperty(fields);
				int fieldLength = fields.length;
				for (int j = 0; j < fieldLength; j++) {
					try {
						String getMethodName = "get" + fields[j].getName().substring(0, 1).toUpperCase() + fields[j].getName().substring(1);
						Method getMethod = entity.getClass().getMethod(getMethodName, new Class[] {});
						String returnType = getMethod.getReturnType().getSimpleName();
						if (checkBaseDataType(returnType)) {
							Object obj = getMethod.invoke(entity, new Object[] {});
							String fieldValue = "";
							if (obj != null){
								fieldValue = obj.toString();
							}
							dataitem.put(fields[j].getName(), fieldValue);
						}
					} catch (Exception e) {
						logger.error(e);
					}
				}
				dataRows.add(dataitem);

			}
		}
		return SUCCESS;
	}

	private boolean decodeQueryCondition() {
		if (getQueryConditions() != null) {
			for (Iterator iter = getQueryConditions().keySet().iterator(); iter
					.hasNext();) {
				String key = (String) iter.next();
				try {
					String inputString = getQueryConditions().get(key);
					inputString = inputString.replaceAll("%26", "&");
					getQueryConditions().put(
							key,
							new String(inputString.getBytes("ISO-8859-1"),
									"GB2312"));
				} catch (UnsupportedEncodingException e) {
					logger.error(e);
					return false;
				}

			}
		}
		return true;
	}
	
	public String updateCustomerStatus(){
		this.result = customerService.updateCustomerStatusById(id, status);
		return SUCCESS;
	}
   
	public String updatePoint(){
		this.result = customerService.updateCustomerPoint(userName,point); 
		return SUCCESS;
	}
	/**
	 * 检查返回类型是否为基本数据类型.
	 * 
	 * @param returnType
	 * @return
	 */
	private boolean checkBaseDataType(String returnType) {
		for (int i = 0; i < Constants.BASE_DATA_TYPE.length; i++) {
			if (Constants.BASE_DATA_TYPE[i].equals(returnType))
				return true;

		}
		return false;
	}

	/**
	 * 此方法用于剔除类中的静态属性，只留下private/public且非静态的的属性
	 */
	private static Field[] removeStaticProperty(Field[] fields) {
		Field[] tempFields = new Field[fields.length];
		int count = 0;
		for (int i = 0; i < fields.length; i++) {
			if (fields[i].getModifiers() <= Modifier.PRIVATE) {
				tempFields[count] = fields[i];
				count++;
			}
		}
		Field[] returnFields = new Field[count];
		for (int i = 0; i < count; i++) {
			returnFields[i] = tempFields[i];
		}
		return returnFields;

	}
		//图片上传Action
	private File filedata;
	private String msg;
	private String err;
	public File getFiledata() {
		return filedata;
	}
	public void setFiledata(File filedata) {
		this.filedata = filedata;
	}
   private Map<String, String> model;
   private String message;
	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public String getErr() {
		return err;
	}

	public void setErr(String err) {
		this.err = err;
	}

	public Map getModel() {
		return model;
	}

	public void setModel(Map model) {
		this.model = model;
	}

	public  String  uploadImage() throws Exception{
		String realpath = ServletActionContext.getServletContext().getRealPath("admin/uploadImages");
		String imageName ="";
		if(filedata!=null){
			Long now = System.currentTimeMillis();
			imageName =now.toString()+".jpg";
			File savefile = new File(new File(realpath),imageName);
			if(!savefile.getParentFile().exists()) 
				{
				savefile.getParentFile().mkdirs();
				}
			FileUtils.copyFile(filedata, savefile);
			msg ="/BNRF/admin/uploadImages/" + imageName;  
	        err="";  
	        printInfo( err, msg);  
			/*
			this.msg=imageName;
			model = new HashMap<String, String>();
	        model.put("msg", imageName);
	        model.put("error", "");
			message = JSONUtil.serialize(this.getModel());
			*/
		}
		return SUCCESS;
	}
	public void printInfo(String err,String newFileName) {  
        message = "{\"err\":\"" + err + "\",\"msg\":\"" + newFileName  
                        + "\"}";  
          
    }  
	public Integer getTotal() {
		return total;
	}

	public void setTotal(Integer total) {
		this.total = total;
	}

	public Integer getRecords() {
		return records;
	}

	public void setRecords(Integer records) {
		this.records = records;
	}

	public Integer getPage() {
		return page;
	}

	public void setPage(Integer page) {
		this.page = page;
	}

	public String getSidx() {
		return sidx;
	}

	public void setSidx(String sidx) {
		this.sidx = sidx;
	}

	public String getSord() {
		return sord;
	}

	public void setSord(String sord) {
		this.sord = sord;
	}

	public Integer getRows() {
		return rows;
	}

	public void setRows(Integer rows) {
		this.rows = rows;
	}
	/**
	 * @return dataRows
	 */
	public List<Map<String, Object>> getDataRows() {
		return dataRows;
	}

	/**
	 * @param dataRows
	 *            要设置的 dataRows
	 */
	public void setDataRows(List<Map<String, Object>> dataRows) {
		this.dataRows = dataRows;
	}
    public String addCustomer(){
    	Customer customer = new Customer();
    	customer.setEmail(email);
    	customer.setUserName(userName);
    	customer.setPassword(password);
    	customer.setRealName(realName);
    	customer.setPhone(phone);
    	customer.setAddress(address);
    	customer.setBirth(birth);
    	customer.setPoint(0);
    	customer.setStatus(1);
    	this.result=customerService.addCustomer(customer);
    	model = new HashMap<String, String>();
    	model.put("result", result);
    	return SUCCESS;
    }
    public String login(){
    	Customer customer = customerService.getCustomerByName(userName);
    	if(customer==null){
    		this.result="none";
    	}
    	else if(customer.getPassword().equals(password)){
    		ActionContext.getContext().getSession().put("customerLogin", userName);
    		this.result="success";
    	}else{
    		this.result="fail";
    	}
    	model = new HashMap<String, String>();
    	model.put("result", result);
    	return SUCCESS;
    }
}
